<template>
    <!-- 主要内容区域 -->
    <main class="flex-grow p-6">
        <div class="bg-white rounded-lg shadow p-6">
            <!-- 搜索和筛选区域 -->
            <div class="flex space-x-4 mb-6">
                <el-input v-model="searchQuery" placeholder="请输入岗位名称" class="w-64" />
                <el-select v-model="selectedType" placeholder="岗位描述" class="w-48">
                    <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-select v-model="selectedDepartment" placeholder="岗位专业" class="w-48">
                    <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-button type="primary" @click="searchPositions" class="!rounded-button whitespace-nowrap">搜索</el-button>
                <el-button @click="resetSearch" class="!rounded-button whitespace-nowrap">重置</el-button>
            </div>
            <!-- 功能按钮组 -->
            <div class="flex space-x-4 mb-6">
                <el-button type="danger" class="!rounded-button whitespace-nowrap" @click="handleDelete">
                    <el-icon class="mr-1"><Delete /></el-icon>删除岗位
                </el-button>
            </div>
            <!-- 岗位数据表格 -->
            <el-table :data="positionsData" style="width: 100%" @selection-change="handleSelectionChange" >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="id" label="岗位编号" width="120" />
                <el-table-column prop="jobName" label="岗位名称" width="120" />
                <el-table-column prop="company" label="发布公司" width="120" />
                <el-table-column prop="required" label="岗位描述"
                                 width="240" show-overflow-tooltip
             />
                <el-table-column prop="salary" label="薪资范围" />
                <el-table-column prop="address" label="工作地点" />
                <el-table-column prop="jobMajor" label="岗位专业" width="120" />
                <el-table-column prop="createTime" label="创建时间" width="180" :formatter="formatDate"/>
                <el-table-column label="状态" width="120">
                    <template #default="scope">
                        <el-button :type="scope.row.status === 1 ? 'success' : 'warning'" size="small" class="!rounded-button whitespace-nowrap">
                            {{ scope.row.status === 1 ? '已通过' : '未通过' }}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" width="200">
                    <template #default="scope">
                        <el-button size="small" @click="edit(scope.row)" class="!rounded-button whitespace-nowrap">编辑</el-button>
                        <el-button size="small" type="primary" @click="viewPosition(scope.row)" class="!rounded-button whitespace-nowrap">查看</el-button>
                        <el-button size="small" type="danger" @click="showDeleteConfirm(scope.row)" class="!rounded-button whitespace-nowrap">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="flex justify-between items-center mt-4">
                <span class="text-sm text-gray-500">共 100 条</span>
                <el-pagination
                    :current-page="currentPage"
                    :page-size="pageSize"
                    :total="totalItems"
                    :page-sizes="[10, 20, 30, 50]"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>

            <!-- 查看岗位信息弹窗 -->
            <el-dialog title="查看岗位" v-model="viewPositionDialogVisible">
                <el-form :model="viewForm">
                    <el-form-item label="岗位编号" label-width="100px">
                        <el-input v-model="viewForm.id" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="岗位名称" label-width="100px">
                        <el-input v-model="viewForm.jobName" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="发布公司" label-width="100px">
                        <el-input v-model="viewForm.company" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="岗位需求" label-width="100px">
                        <el-input v-model="viewForm.required" type="textarea" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="工作地点" label-width="100px">
                        <el-input v-model="viewForm.address" type="textarea" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="薪资范围" label-width="100px">
                        <el-input v-model="viewForm.salary" type="textarea" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="岗位专业" label-width="100px">
                        <el-input v-model="viewForm.jobMajor" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="创建时间" label-width="100px">
                        <el-input v-model="viewForm.createdTime" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="状态" label-width="100px">
                        <el-input v-model="viewForm.status" disabled></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="viewPositionDialogVisible = false">关闭</el-button>
                    </span>
                </template>
            </el-dialog>

            <!-- 编辑岗位信息弹窗 -->
            <el-dialog title="编辑岗位" v-model="editPositionDialogVisible">
                <el-form :model="editForm">
                    <el-form-item label="岗位编号" label-width="100px">
                        <el-input v-model="editForm.id" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="岗位名称" label-width="100px">
                        <el-input v-model="editForm.jobName"></el-input>
                    </el-form-item>
                    <el-form-item label="发布公司" label-width="100px">
                        <el-input v-model="editForm.company"></el-input>
                    </el-form-item>
                    <el-form-item label="岗位描述" label-width="100px">
                        <el-input v-model="editForm.required" type="textarea"></el-input>
                    </el-form-item>
                    <el-form-item label="工作地点" label-width="100px">
                        <el-input v-model="editForm.address" type="textarea" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="薪资范围" label-width="100px">
                        <el-input v-model="editForm.salary" type="textarea" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="岗位专业" label-width="100px">
                        <el-input v-model="editForm.jobMajor"></el-input>
                    </el-form-item>
                    <el-form-item label="创建时间" label-width="100px">
                        <el-input v-model="editForm.createdAt" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="状态" label-width="100px">
                        <el-select v-model="editForm.status" placeholder="状态">
                            <el-option label="通过" value=1 />
                            <el-option label="未通过" value=0 />
                        </el-select>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="editPositionDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="updatePosition">保存</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </main>
</template>


<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ElTable } from 'element-plus'
import {getAllJobRecruitment,updateWorkPost} from "../../api/admin/position.js"
import { Search, Plus, Delete } from '@element-plus/icons-vue';
onMounted(()=>{
    getAll_Job(pagination)
})
function getAll_Job(data) {
    getAllJobRecruitment(data).then(function (response) {
            positionsData.value=response.items[0]
        console.log(positionsData)
    })
}

// 日期格式化方法
const formatDate = (row, column, cellValue) => {
    if (!cellValue) return '';
    const d = new Date(cellValue);
    return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`; // 返回 yyyy-mm-dd 格式
};
const searchQuery = ref('');
const selectedType = ref('');
const selectedDepartment = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const totalItems = ref(100);
// 分页
const pagination = ref({
    currentPage: 1,
    pageSize: 10,
    total: 100
});
const typeOptions = [
    { value: 'technical', label: '技术岗位' },
    { value: 'management', label: '管理岗位' },
    { value: 'support', label: '支持岗位' },
];

const departmentOptions = [
    { value: 'it', label: '信息技术' },
    { value: 'hr', label: '人力资源' },
    { value: 'finance', label: '财务' },
];

let positionsData = ref([]);


const searchPositions = () => {
    ElMessage.success('搜索功能已触发');
};

const editPositionDialogVisible = ref(false);
const viewPositionDialogVisible = ref(false);
const addPositionDialogVisible = ref(false);

const viewForm = ref({});
let editForm = ref({});
const addForm = ref({});

//编辑弹窗
const edit = (row) => {
    editForm.value = { ...row };
    editPositionDialogVisible.value = true;
};
//编辑保存
const updatePosition = async () => {
  const index = positionsData.value.findIndex(item => item.id === editForm.id);
  const editData = await updateWorkPost(editForm.value).then((res) => {
    if (res.data.code ===200){
      ElMessage.success("编辑成功")
      getAllPoststation()
      editPositionDialogVisible.value = false;
    }else{
      ElMessage.error("编辑失败")
      editPositionDialogVisible.value = false;
      throw new Error("编辑内容保存失败")
    }
    return res.data
  })
  console.log(editData)
};
//查看弹窗
const viewPosition = (row) => {
    viewForm.value = { ...row };
    viewPositionDialogVisible.value = true;
};


//批量删除
const selectedRows = ref([]);

const handleSelectionChange = (rows) => {
    selectedRows.value = rows;
};

const handleDelete = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择需要删除的岗位');
        return;
    }

    await ElMessageBox.confirm('确定要删除所选岗位吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).catch(() => {
    ElMessage.info("取消删除!");
    return new Promise(() => {});
  });
  const ids = selectedRows.value.map((item) => item.id);
  const res = await batchDelFrom(ids);
  if (res.data.code === 200) {
    ElMessage.success("删除成功");
    getAllPoststation()
  } else {
    ElMessage.error("删除失败");
  }
};

const handleSizeChange = (val) => {
    pageSize.value = val;
    ElMessage.info(`每页显示 ${val} 条`);
};

const handleCurrentChange = (val) => {
    currentPage.value = val;
    ElMessage.info(`当前页：${val}`);
};

const showDeleteConfirm = async (row) => {
    ElMessageBox.confirm(`确定要删除岗位 ${row.jobName} 吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).catch(() => {
    ElMessage.info("取消删除!")
    return new Promise(() => {})
  }) 
  const res = await delFrom(row.id)
  getAllPoststation()
  console.log(res)
};
</script>


<style scoped>
/* 自定义样式 */
.el-input__wrapper {
    background-color: #fff;
    border: 1px solid #dcdfe6;
}
.el-select__wrapper {
    background-color: #fff;
    border: 1px solid #dcdfe6;
}
.el-button {
    font-weight: 500;
}
.el-table {
    --el-table-border-color: #e5e7eb;
    --el-table-header-bg-color: #f3f4f6;
    --el-table-row-hover-bg-color: #f9fafb;
}
</style>
